//
//  NewsViewController.swift
//  ReadHub
//
//  Created by 龙轶群 on 2017/7/30.
//  Copyright © 2017年 longyiqun. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import DGElasticPullToRefresh
import FDTemplateLayoutCell
import AlamofireImage
import SwiftMoment
import MMCardView
import PKHUD
import SwiftWebVC

class NewsViewController: UIViewController{
    
    @IBOutlet weak var cardCollection: MMCollectionView!
    @IBOutlet weak var refreshBtn: UIButton!
    
    // 所有新闻集合
    var news: NSMutableArray = []
    // 当前页最后一个话题publish date
    var lastTimeStamp: String = ""
    var firstTimeStamp: String = ""
    // 当前页最开始一个话题OrderID
    var firstOrder: Int = 0
    //用了记录当前是否允许加载新数据（正则加载的时候会将其设为false，放置重复加载）
    var loadMoreEnable = true

    // 新动态
    var newsCount: Int = 0
    var timer: Timer?


    // 主流程
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 一进来就显示刷新中
        HUD.show(.labeledProgress(title: "", subtitle: ""))
        
        // 注册不同的Nib
        cardCollection.register(UINib(nibName: "NewsCell", bundle: nil), forCellWithReuseIdentifier: "CardCell")
        cardCollection.register(UINib(nibName: "NewsCell2", bundle: nil), forCellWithReuseIdentifier: "CardCell2")
        cardCollection.register(UINib(nibName: "NewsCell3", bundle: nil), forCellWithReuseIdentifier: "CardCell3")
        cardCollection.register(UINib(nibName: "NewsCell4", bundle: nil), forCellWithReuseIdentifier: "CardCell4")
        cardCollection.register(UINib(nibName: "NewsCell5", bundle: nil), forCellWithReuseIdentifier: "CardCell5")
        
        //cardCollection背景色
        cardCollection.backgroundColor = Constants.mainBackGroundColor
        
        //加载Layout
        if let layout = cardCollection.collectionViewLayout as? CustomCardLayout {
            layout.titleHeight = 100.0
            layout.bottomShowCount = 3
            layout.cardHeight = 300
            layout.showStyle = .cover
        }
        
      
        
        // 取数据(第一次,所以是false)
        getTopics(isMore: false)
    }
    
    // view显示的时候把timer启动
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 10秒钟刷新一次
        timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(self.hasNewNews), userInfo: nil, repeats: true)
    }
    
    // view消失的时候把newly去掉, timer去掉
    override func viewWillDisappear(_ animated: Bool){
        super.viewWillDisappear(animated)
        
//        newly.hideUpdate()
//        timer?.invalidate()
//        timer = nil
    }
    
    // 查看是否有新的新闻
	@objc internal func hasNewNews() -> () {
        
//        var parameters: Parameters = [:]
//        
//        // 只取2条
//        parameters = ["pageSize": "2"]
        
        // 解析News最新的
        Alamofire.request(Constants.newsURL).responseJSON { response in
            if let JSONEntity = response.result.value {
                let jsonData = JSON(JSONEntity)
                
                // 临时Array
                let tempArray: NSMutableArray = []
                
                // 判断节点数量大于0
                if (jsonData["data"].count > 0){
                    
                    // 循环取News填充数组
                    for (_, newsDataArray): (String, JSON) in jsonData["data"] {
                        
                        // 临时News对象
                        let tempNews = News()
                        
                        // Topic基本信息
                        tempNews.id = newsDataArray["id"].string
                        tempNews.title = newsDataArray["title"].string
                        tempNews.siteName = newsDataArray["siteName"].string
                        tempNews.publishDate = newsDataArray["publishDate"].string
                        tempNews.url = newsDataArray["url"].string
                        tempNews.summary = newsDataArray["summary"].string
                        
                        // 添加News到临时数组中
                        tempArray.add(tempNews)
                    }
                    
                    //如果取得的第一个New的时间大于之前记录的最大时间, 则显示有新内容
                    if ((tempArray[0] as! News).publishDate! != self.firstTimeStamp) {
                        print (self.firstTimeStamp)
//                        self.newly.showUpdate(message: "新内容!")
                    }
                }
            }
        }
    }

    
    func umSocialParentView(_ defaultSuperView: UIView!) -> UIView! {
        return defaultSuperView
    }
    

    
    // 点击刷新按钮
    @IBAction func tappedRefreshButton(_ sender: UIButton) {
        
        if (news.count > 0 ) {
            
            // 清空数据源
            //news.removeAllObjects()
            
            // 显示Loading
            HUD.show(.labeledProgress(title: "", subtitle: ""))
            
            // 取数据 (不是更多)
            getTopics(isMore: false)
        }
    }
    
    // 获取数据主方法
    internal func getTopics(isMore: Bool) -> () {
        
        var parameters: Parameters = [:]
        
        // 根据是不是获取更多来定义Parameters
        if (!isMore) {
            news = []
            parameters = ["pageSize": "20"]
        } else {
            
            // 如果是获取更多, 则标记为不能再获取新数据的状态
            loadMoreEnable = false
            parameters = ["lastCursor": self.lastTimeStamp, "pageSize": "10"]
        }
        
        // 解析News最新的
        Alamofire.request(Constants.newsURL, parameters: parameters).responseJSON { response in
            if let JSONEntity = response.result.value {
                let jsonData = JSON(JSONEntity)
                
                // 判断节点数量大于0
                if (jsonData["data"].count > 0){
                    
                    // 循环取News填充数组
                    for (_, newsDataArray): (String, JSON) in jsonData["data"] {
                        
                        // 临时News对象
                        let tempNews = News()
                        
                        // Topic基本信息
                        tempNews.id = newsDataArray["id"].string
                        tempNews.title = newsDataArray["title"].string
                        tempNews.siteName = newsDataArray["siteName"].string
                        tempNews.publishDate = newsDataArray["publishDate"].string
                        tempNews.url = newsDataArray["url"].string
                        tempNews.summary = newsDataArray["summary"].string
                       
                        // 添加News到数组中
                        self.news.add(tempNews)
                    }
                }
                
                // 数据获取完更新本地的一些tag
                if (self.news.count > 0) {
                    
                    self.lastTimeStamp = (self.news.lastObject as! News).publishDate!
                    self.firstTimeStamp = (self.news.firstObject as! News).publishDate!
                    
                    print ("最后1个元素的标准时间：" + self.lastTimeStamp)
                    print ("第1个元素的标准时间：" + self.firstTimeStamp)
                    
                    // 当前时间+8换成本地时间
                    let timeMoment = moment(self.lastTimeStamp)! + 8.hours
                    
                    
                    //时间戳
                    let timeInterval:TimeInterval = timeMoment.date.timeIntervalSince1970
                    let timeStamp = Int(timeInterval)
                    let timeStampString = String(timeStamp)
                    
                    print("时间戳：" + timeStampString + "000")
                    
                    // 换成毫秒的TimeStamp
                    self.lastTimeStamp = timeStampString + "000"
                    
                } else {
                    self.lastTimeStamp = ""
                    self.firstTimeStamp = ""
                }
            }
            // 刷新页面
            self.cardCollection.reloadData()
            HUD.hide(afterDelay: 1)
        }
    }
    
    // 销毁页面的时候注销newly和timer
    deinit{
//        newly.hideUpdate()
//        timer?.invalidate()
//        timer = nil
    }

}

// 显示卡片主方法
extension NewsViewController: UICollectionViewDataSource {
    
    // section返回为1
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        self.cardCollection.collectionViewLayout.invalidateLayout()
        return 1
    }
    
    // count返回为news的数量
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return news.count
    }
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        return self.card(collectionView: collectionView, cellForItemAt: indexPath)
    }
    
    
    // 绘制每个cell
    fileprivate func card(collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        var cellType = ""
        
        // 根据index获取Nib的模板
        if (indexPath.row % 5 == 0) {
            cellType = "CardCell"
        } else  if (indexPath.row % 5 == 1){
            cellType = "CardCell2"
        } else  if (indexPath.row % 5 == 2){
            cellType = "CardCell3"
        } else  if (indexPath.row % 5 == 3){
            cellType = "CardCell4"
        } else  if (indexPath.row % 5 == 4){
            cellType = "CardCell5"
        }
        
        // 重用cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellType, for: indexPath)
        
        // 开始填充cell
        switch cell {
        case let c as NewsCell:
            
            c.titleLabel.text = (news[indexPath.row] as! News).title
            
            if (cellType == "CardCell") {
                c.backgroundColor = UIColor("#2578b5")
            } else if (cellType == "CardCell2") {
                c.backgroundColor = UIColor("#304758")
            } else if (cellType == "CardCell3") {
                c.backgroundColor = UIColor("#17507d")
            } else if (cellType == "CardCell4") {
                c.backgroundColor = UIColor("#3c5e91")
            } else if (cellType == "CardCell5") {
                c.backgroundColor = UIColor("#0041a5")
            }
       
            c.summaryLabel.text = (news[indexPath.row] as! News).summary
            
            c.clickCallBack {
                
//                let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
//                let destination = storyboard.instantiateViewController(withIdentifier: "WebViewController") as! WebViewController
//                destination.modalTransitionStyle = .crossDissolve
//                    
//                // 传url值过去
//                destination.url = ((self.news[indexPath.row]) as! News).url
//                destination.shareTitle = ((self.news[indexPath.row]) as! News).title
//                
//                // 展示
//                self.present(destination, animated: true, completion: nil)
				
				
				let pageURL = ((self.news[indexPath.row]) as! News).url
				
				let webVC = SwiftModalWebVC(urlString: pageURL!, theme: .dark, dismissButtonStyle: .arrow)
				
				self.present(webVC, animated: true, completion: nil)
				

			}
            
            // 取时间
            var timeMoment = moment() - moment((news[indexPath.row] as! News).publishDate!)!
            
            // 换成本地+8时区
            timeMoment = timeMoment - 8.hours
            
            // 设置时间
            if (timeMoment.seconds < 60) {
                c.publishDateLabel.text = "现在"
            } else if (timeMoment.minutes < 60) {
                c.publishDateLabel.text = String(Int(timeMoment.minutes)) + " 分钟前"
            } else if (timeMoment.hours < 24) {
                c.publishDateLabel.text = String(Int(timeMoment.hours)) + " 小时前"
            } else {
                c.publishDateLabel.text = String(Int(timeMoment.days)) + " 天前"
            }
            
        default:
            break
        }
        return cell
    }
    
    // 划到最后一个cell的中间的时候,加载更多
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if(scrollView.contentOffset.y == scrollView.contentSize.height - scrollView.frame.size.height) {
            getTopics(isMore: true)
        }
    }
}

// 扩展TechViewController支持Layout
extension NewsViewController: UICollectionViewDelegateFlowLayout {
    public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        print("DE-Click " + String(indexPath.row))
    }
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Click " + String(indexPath.row))
    }
    
    func invalidateLayout() {
        
    }

}


